#include "sdl_event.h"

#define STOP_WAITING_CODE 5060


sdl::Event::Event()
{
	memset(&_event, 0, sizeof(SDL_Event));
}


void sdl::Event::wait() throw (sdl::Exception)
{
	const Uint8* keyState;
	int keysDown = 0;

	for (;;) {
		if (SDL_PollEvent(&_event)) {
			if (_event.type == SDL_USEREVENT &&
				_event.user.code == STOP_WAITING_CODE)
			{
				break;
			}
			else if (_event.type == SDL_KEYDOWN)
				keysDown++;
			else if (_event.type == SDL_KEYUP)
				keysDown--;
			
			fire(sdl::EventListener::NewEvent(), &_event);
		}

		if (keysDown > 0) {
			keyState = SDL_GetKeyState(NULL);
			fire(sdl::EventListener::KeyPressed(), keyState);
		}
		else SDL_Delay(10);
	}
}


void sdl::Event::stopWaiting()
{
	sendUserEvent(STOP_WAITING_CODE);
}


void sdl::Event::sendUserEvent(int code, void* arg1, void* arg2)
{
	SDL_Event event;

	event.type = SDL_USEREVENT;
	event.user.code = code;
	event.user.data1 = arg1;
	event.user.data2 = arg2;

	SDL_PushEvent(&event);
}

